package com.shop.utils;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Locale;

import org.xhtmlrenderer.pdf.ITextRenderer;

import com.lowagie.text.pdf.BaseFont;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * 
* <p>Title: PdfHelper</p>
* <p>Description: </p>
* @Project kevin-common-utils
* @Package com.kevin.common.utils.util
* @author Kevin Lv 
* @date 2016年11月14日 下午3:38:03
* @version V1.0
 */
public class PdfHelper {

	/**
	 * 获取Freemarker配置
	 * @param templatePath
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("deprecation")
	private static Configuration getFreemarkerConfig(String templatePath) throws IOException {
		Configuration config = new Configuration();
		config.setDirectoryForTemplateLoading(new File(templatePath));
		config.setEncoding(Locale.CHINA, "utf-8");
		return config;
	}
	
	/**
	 * 获取类路径
	 * @return
	 */
	public static String getPath(){
		return PdfHelper.class.getClassLoader().getResource("").toString().replace("file:/", "").replace("target/test-classes/", "src/main/resources/");
	}
	
	public static ITextRenderer getRender() throws Exception {

		ITextRenderer render = new ITextRenderer();
		String path = getPath();
		String os = System.getProperty("os.name");  
		if(!os.toLowerCase().startsWith("win")){  
		   path = "/" + path;
		}
		//添加字体，以支持中文
		render.getFontResolver().addFont(path + "template/ARIALUNI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		render.getFontResolver().addFont(path + "template/SIMSUN.TTC", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

		return render;
	}

	//获取要写入PDF的内容
	public static String getPdfContent(String ftlPath, String ftlName, Object o) throws IOException, TemplateException {
		return useTemplate(ftlPath, ftlName, o);
	}

	//使用freemarker得到html内容
	@SuppressWarnings("deprecation")
	public static String useTemplate(String ftlPath, String ftlName, Object o) throws IOException, TemplateException {

		String html = null;

		Template tpl = getFreemarkerConfig(ftlPath).getTemplate(ftlName);
		tpl.setEncoding("UTF-8");

		StringWriter writer = new StringWriter();
		tpl.process(o, writer);
		writer.flush();
		html = writer.toString();
		
		return html;
	}
	

}
